package mysql

import (
	"bluebell/models"
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
)

const secret = "yt20010310"

// 把每一步数据库操作封装成函数
// 待logic层根据业务需求调用
// CheckUserExist 检查用户是否存在
func CheckUserExist(username string) (err error) {
	if db == nil {
		return fmt.Errorf("数据库连接未初始化")
	}
	sqlStr := `select count(user_id) from user where username = ?`
	var count int64
	if err = db.Get(&count, sqlStr, username); err != nil {
		return err
	}
	if count > 0 {
		return errors.New("用户已存在")
	}
	return nil
}

// InsertUser 向数据库中插入一条新的用户记录
func InsertUser(user *models.User) (err error) {
	user.Password = encryptPassword(user.Password)
	//执行SQL入库操作
	sqlStr := `insert into user(user_id,username,password) values(?,?,?)`
	_, err = db.Exec(sqlStr, user.UserId, user.Username, user.Password)
	return err
}

func encryptPassword(oPassword string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPassword)))
}
